#include "server_fun.h"

int main(int argc, const char *argv[])
{
	//初始化数据库-->
	db = sqlite3_init("staff_system.db");
	if(db == NULL){
		printf("sqlite3 init err.\n");
		return 0;
	}else{
		printf("sqlite3 init ok.\n");
	}
	//<--初始化数据库
	//初始化网络连接-->	
	int sockfd = IPV4_init(SOCK_STREAM,SERVER,argc,argv);
	if(sockfd < 0){
		printf("IPV4 init err.\n");
		return 0;
	}else{
		printf("IPV4 init ok.\n");
	}
	//<--初始化网络连接
	//epoll
	struct epoll_event event;//定义epoll事件
	struct epoll_event events_list[20];//定义epoll事件集合
	int epfd = epoll_create(1);//创建句柄
	event.data.fd = sockfd;//
	event.events = EPOLLIN|EPOLLET;//可读,电平触发
	epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);//注册fd到epfd中
	while(1)
	{
		int epct = epoll_wait(epfd,events_list,20,-1);//等待事件发生
		int i;
		TranMsg *tranmsg = malloc(sizeof(TranMsg));//开辟空间
		memset(tranmsg,0,sizeof(TranMsg));//初始化
		for(i=0;i<epct;i++)
		{
			if(events_list[i].data.fd == sockfd)//新连接
			{
				int acceptfd = accept(sockfd, NULL, NULL);
				event.data.fd = acceptfd;
				event.events = EPOLLIN|EPOLLET;
				epoll_ctl(epfd,EPOLL_CTL_ADD,acceptfd,&event);//注册
			}else
			{
				int rlen = read(events_list[i].data.fd,tranmsg,sizeof(TranMsg));//读数据
				if(rlen<=0)
				{
					printf("%d connect disconnected\n",events_list[i].data.fd);
					close(events_list[i].data.fd);
					epoll_ctl(epfd,EPOLL_CTL_DEL,events_list[i].data.fd,&event);//删除事件
					continue;
				}else{
					recv_msg_server_fun(events_list[i].data.fd,tranmsg);
				}
			}
		}
		free(tranmsg);//释放空间
	}
	sqlite3_close(db);
	return 0;
}
